package com.rtx.edi.platform.jobextend.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.api.annotation.DataSourceAnnotation;
import com.rtx.edi.platform.application.mapper.PlApplicationEnvironmentMapper;
import com.rtx.edi.platform.baseinfo.mapper.PlApibaseinfoMapper;
import com.rtx.edi.platform.jobextend.bean.dto.JobConfigDTO;
import com.rtx.edi.platform.jobextend.bean.po.PlJob;
import com.rtx.edi.platform.jobextend.bean.po.PlJobDetail;
import com.rtx.edi.platform.jobextend.bean.po.PlJobMapping;
import com.rtx.edi.platform.jobextend.mapper.PlJobDetailMapper;
import com.rtx.edi.platform.jobextend.mapper.PlJobMapper;
import com.rtx.edi.platform.jobextend.mapper.PlJobMappingMapper;
import com.rtx.edi.platform.jobextend.service.ApiJobService;

/**
 * APIJOB服务
 */
@Service
public class ApiJobServiceImpl implements ApiJobService {

    @Autowired
    private PlJobMapper plJobMapper;

    @Autowired
    private PlJobDetailMapper plJobDetailMapper;

    @Autowired
    private PlJobMappingMapper plJobMappingMapper;

    @Autowired
    private PlApplicationEnvironmentMapper plApplicationEnvironmentMapper;

    @Autowired
    private PlApibaseinfoMapper plApibaseinfoMapper;

    @Override
    public JobConfigDTO selectConfig(String jobName) {
        JobConfigDTO jobConfigDTO = new JobConfigDTO();
        //获取定时任务
        LambdaQueryWrapper<PlJob> query1 = Wrappers.lambdaQuery();
        query1.eq(PlJob::getJobName,jobName);
        PlJob plJob = plJobMapper.selectOne(query1);
        jobConfigDTO.setPlJob(plJob);
        //获取定时任务详情
        LambdaQueryWrapper<PlJobDetail> query2 = Wrappers.lambdaQuery();
        query2.eq(PlJobDetail::getJobId,plJob.getId());
        jobConfigDTO.setPlJobDetails(plJobDetailMapper.selectList(query2));
        //获取定时任务字段映射
        LambdaQueryWrapper<PlJobMapping> query3 = Wrappers.lambdaQuery();
        query3.eq(PlJobMapping::getJobId,plJob.getId());
        jobConfigDTO.setPlJobMappings(plJobMappingMapper.selectList(query3));
        //获取目标API
        if(plJob.getTargetApiId() != null){
            jobConfigDTO.setApiInfo(plApibaseinfoMapper.selectById(plJob.getTargetApiId()));
        }
        //获取目标环境
        if(plJob.getEnvironmentId() != null){
            jobConfigDTO.setEnvironment(plApplicationEnvironmentMapper.selectById(plJob.getEnvironmentId()));
        }
        return jobConfigDTO;
    }

    @DataSourceAnnotation
    @Override
    public Integer executeSql(String whseid, String sql) {
        return plJobMappingMapper.update(sql);
    }
}
